<template>
    <div id="login" :style="mainStyles">
      <div id="title">
        <img src="./images/logo.png" alt="">
        移动沈农
      </div>
      <form>
        <input v-model.trim="account" type="text" id="account" placeholder="请输入教务处账号">
        <input v-model.trim="pwd" type="password" id="pwd" placeholder="请输入教务处密码" autocomplete='pwd'>
      </form>
      <mt-button
        class="login"
        @click.native="login"
        @keyup.enter="login"
        type="primary"
        :disabled="btnDisabled"
        size="large">
        登录
      </mt-button>
    </div>
</template>
<script>
import { mapGetters } from 'vuex';
import { Toast,Indicator } from 'mint-ui';
import fetch from '@/libs/fetch';
import courseClean from '@/libs/courseClear';
import storage from '@/libs/storage';

export default {
  data(){
    return {
      btnDisabled: false,
      account: '195140040',
      pwd: '1937915896',
      loadStatus: 0 // 判断登录是否成功
    }
  },
  computed: {
    mainStyles(){
      let height = window.innerHeight;
      return {
        height: height + 'px'
      }
    },
    ...mapGetters([
      'getUserAccount',
      'getUserInfo'
    ])
  },
  mounted(){
    this.isNeedLogin();
    // 判断是否需要刷新页面来清空store缓存
    let isReload = this.$store.state.info.isReload;
    if(isReload){
      window.location.reload();
    }
  },
  methods:{
    isNeedLogin(){
      let timeStamp = this.getTimeStamp();
      let account = storage.getItem('account');
      let userInfo = storage.getItem('userInfo');
      let sTimeStamp;
      if(account){
        sTimeStamp = storage.getItem('ik').d;
        let duration = parseInt(timeStamp) - parseInt(sTimeStamp);
        if(duration < 24 * 60 * 60 * 1000){
          this.requestOpenDate();
          this.requestCourse();
          this.$store.commit('setUserAccount',account);
          this.$store.commit('setUserInfo', userInfo);
          this.$router.replace('/main/course');
        }else{
          this.account = account.account;
          this.pwd = account.pwd;
          this.requestLogin();
        }
      }
    },
    login(){
      // 登录时正则匹配输入的账号密码是否正确
      let accountReg = /\d{9,10}/;
      if(!accountReg.test(this.account)){
        Toast('账号错误');
        return;
      }
      if(!this.pwd){
        Toast('请输入密码');
        return;
      }
      this.requestLogin();
    },
    requestLogin(){
      this.btnDisabled = true;
      Indicator.open('加载中...');
      fetch.post({
        url: '/login',
        data: {
          account: this.account,
          password: this.pwd
        },
        success: (res) => {
          console.log(res);
          if(res.data.code === 0){
            this.$store.commit('setUserAccount',{
              account: this.account,
              pwd: this.pwd
            });
            this.$store.commit('setUserInfo', res.data.data);
            storage.setItem('ik', {
              i: res.data.data.i,
              k: res.data.data.k,
              d: this.getTimeStamp()
            });
            // 上文中的loadStatus在这里处理并发请求
            this.requestOpenDate();
            this.requestCourse();
            // this.$router.replace('/main/course');
          } else {
            Toast('账号或密码错误');
            this.go('账号或密码错误');
          }
          return true;
        },
        error: (e) => {
          console.log('error', e);
          this.go(e);
        }
      })
    },
    requestOpenDate(){
      fetch.get({
        url: '/openingdate',
        success: (res) => {
          // console.log('open date', res);
          if(res.data.code === 0){
            this.$store.commit('setOpenDate', res.data.data.date);
            this.loadStatus++;
            this.go();
          }
        },
        error: (e) => {
          // console.log('open data e', e);
          this.go(e)
        }
      })
    },
    requestCourse(){
      fetch.post({
        url: '/getCourseInfo',
        data:{
          f:0
        },
        success: (res) => {
          // console.log('getCourseInfo', res);
          let data;
          if(res.data.code === 0){
            // console.log(res);
            // if(res.status !== 9999){
            //   data = courseClean.cleaning(res.data.data);
            // }
            data = courseClean.cleaning(res.data.data);

            this.$store.commit('setCourses', data);
            this.loadStatus++;
            this.go();
          }
        },
        error: (e) => {
          console.log('getCourseInfo', e);
          this.go(e);
        }
      })
    },
    // 每次请求结束后都会调用这个函数，用于判断是否所有请求都加载成功
    // 当有一个请求失败时，提示重新登录
    go(error){
      if(this.loadStatus === 2){
        this.$nextTick(() => {
          Indicator.close();
        })
        this.loadStatus = 0;
        storage.setItem('account', this.getUserAccount);
        storage.setItem('userInfo', this.getUserInfo);
        this.$router.replace('/main/course');
      }
      if(error){
        this.$nextTick(() => {
          Indicator.close();
        })
        Toast('登录失败，请重试');
        this.loadStatus = 0;
        this.btnDisabled = false;
      }
    },
    getTimeStamp(){
      let d = new Date();
      let fmtDate = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
      return (new Date(fmtDate)).getTime();
    }
  }
}
</script>

<style scoped>
#login{
  width: 100%;
  height: 100%;
  background: url('./images/bg.jpg');
  background-size: 100% 100%;
  padding: 50px 20px 0;
  box-sizing: border-box;
}
#title{
  font-size: 20px;
  font-weight: bold;
  color: #ffffff;
}
#title img{
  width: 30px;
  height: 30px;
  vertical-align: middle;
}
input::-webkit-input-placeholder{
  color:#ffffff;
}
#account,
#pwd{
  width: 100%;
  height: 50px;
  background: rgba(0, 0, 0, 0);
  border: 0;
  border-bottom: 1px solid #f4f4f4;
  margin-top: 10px;
  font-size: 18px;
  color: #ffffff;
  outline: 0;
}
.login{
  margin-top: 20px;
}
</style>
